package com.jiazhong.example.project.bookstore.backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiazhong.example.project.bookstore.backend.service.PowerService;
import com.jiazhong.example.project.bookstore.commons.bean.Power;
import com.jiazhong.example.project.bookstore.commons.mapper.PowerMapper;
import com.jiazhong.example.project.bookstore.commons.util.JsonResult;
import com.jiazhong.example.project.bookstore.commons.util.ResultTool;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class PowerServiceImpl extends ServiceImpl<PowerMapper, Power> implements PowerService {
    @Resource
    private PowerMapper powerMapper;

    @Override
    public JsonResult findAllPower() {
        return ResultTool.success(list());
    }

    @Override
    public JsonResult findPowerByUserId(String id) {
        return ResultTool.success(powerMapper.findPowerByUserId2(id));
    }

    @Transactional(rollbackFor = Exception.class)
    public JsonResult updateUserPowers(String userId, List<String> powers) {
        // 1.删除该用户的权限
        powerMapper.removeByUserId(userId);
        // 2.给这个用户添加权限
        for (String power : powers) {
            QueryWrapper<Power> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("name", power);
            Power one = getOne(queryWrapper);
            powerMapper.insertPowerByUserId(userId, one.getId());
        }
        return ResultTool.success("success");
    }
}
